use serde::{Deserialize, Serialize};
use serde_json::{self, Value};
use std::fs::File;
use std::io::{self, Read, Write};
use std::time::{SystemTime, UNIX_EPOCH};

/// 工具类 `JsonUtil` 用于处理 JSON 数据的序列化和反序列化
pub struct JsonUtil;

impl JsonUtil {
    /// 将结构体序列化为 JSON 字符串
    ///
    /// # 参数
    /// * `data` - 要序列化的结构体数据
    ///
    /// # 返回值
    /// 返回包含 JSON 字符串的 `Result<String, io::Error>`
    ///
    /// # 示例
    /// ```
    /// #[derive(Serialize)]
    /// struct Person {
    ///     name: String,
    ///     age: u8,
    /// }
    ///
    /// let person = Person { name: "Alice".to_string(), age: 30 };
    /// let json_str = JsonUtil::serialize(&person);
    /// match json_str {
    ///     Ok(json) => log::info!("Serialized JSON: {}", json),
    ///     Err(e) => log::info!("Error serializing: {}", e),
    /// }
    /// ```
    pub fn serialize<T>(data: &T) -> Result<String, io::Error>
    where
        T: Serialize,
    {
        serde_json::to_string(data)
            .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Serialization error: {}", e)))
    }

    /// 将 JSON 字符串反序列化为指定类型的结构体
    ///
    /// # 参数
    /// * `json_str` - 要反序列化的 JSON 字符串
    ///
    /// # 返回值
    /// 返回包含反序列化后的结构体数据的 `Result<T, io::Error>`
    ///
    /// # 示例
    /// ```
    /// #[derive(Deserialize, Debug)]
    /// struct Person {
    ///     name: String,
    ///     age: u8,
    /// }
    ///
    /// let json_str = r#"{"name": "Alice", "age": 30}"#;
    /// let person = JsonUtil::deserialize::<Person>(json_str);
    /// match person {
    ///     Ok(p) => log::info!("Deserialized struct: {:?}", p),
    ///     Err(e) => log::info!("Error deserializing: {}", e),
    /// }
    /// ```
    pub fn deserialize<'a, T>(json_str: &'a str) -> Result<T, io::Error>
    where
        T: Deserialize<'a>,
    {
        serde_json::from_str(json_str)
            .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Deserialization error: {}", e)))
    }

    /// 将结构体序列化为 JSON 文件
    ///
    /// # 参数
    /// * `data` - 要序列化的结构体数据
    /// * `file_path` - JSON 文件路径
    ///
    /// # 返回值
    /// 返回包含操作结果的 `Result<(), io::Error>`
    ///
    /// # 示例
    /// ```
    /// #[derive(Serialize)]
    /// struct Person {
    ///     name: String,
    ///     age: u8,
    /// }
    ///
    /// let person = Person { name: "Alice".to_string(), age: 30 };
    /// let result = JsonUtil::serialize_to_file(&person, "person.json");
    /// match result {
    ///     Ok(_) => log::info!("Serialized to file successfully."),
    ///     Err(e) => log::info!("Error serializing to file: {}", e),
    /// }
    /// ```
    pub fn serialize_to_file<T>(data: &T, file_path: &str) -> Result<(), io::Error>
    where
        T: Serialize,
    {
        let json_str = JsonUtil::serialize(data)?;
        let mut file = File::create(file_path)?;
        file.write_all(json_str.as_bytes())?;
        Ok(())
    }

    /// 将 JSON 文件反序列化为指定类型的结构体
    ///
    /// # 参数
    /// * `file_path` - JSON 文件路径
    ///
    /// # 返回值
    /// 返回包含反序列化后的结构体数据的 `Result<T, io::Error>`
    ///
    /// # 示例
    /// ```
    /// #[derive(Deserialize, Debug)]
    /// struct Person {
    ///     name: String,
    ///     age: u8,
    /// }
    ///
    /// let person = JsonUtil::deserialize_from_file::<Person>("person.json");
    /// match person {
    ///     Ok(p) => log::info!("Deserialized from file: {:?}", p),
    ///     Err(e) => log::info!("Error deserializing from file: {}", e),
    /// }
    /// ```
    pub fn deserialize_from_file<T>(file_path: &str) -> Result<T, io::Error>
    where
        T: for<'de> Deserialize<'de>,
    {
        let mut file = File::open(file_path)?;
        let mut json_str = String::new();
        file.read_to_string(&mut json_str)?;
        JsonUtil::deserialize(&json_str)
    }

    /// 将当前时间戳转换为 JSON 友好的日期字符串
    ///
    /// # 返回值
    /// 返回包含当前时间戳的 `String`
    ///
    /// # 示例
    /// ```
    /// let timestamp = JsonUtil::current_timestamp();
    /// log::info!("Current timestamp: {}", timestamp);
    /// ```
    pub fn current_timestamp() -> String {
        let start = SystemTime::now();
        let since_the_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards");
        let datetime = chrono::NaiveDateTime::from_timestamp(since_the_epoch.as_secs() as i64, 0);
        datetime.format("%Y-%m-%d %H:%M:%S").to_string()
    }

    /// 将 JSON 字符串解析为 `serde_json::Value` 对象
    ///
    /// # 参数
    /// * `json_str` - 要解析的 JSON 字符串
    ///
    /// # 返回值
    /// 返回包含解析结果的 `Result<Value, io::Error>`
    ///
    /// # 示例
    /// ```
    /// let json_str = r#"{"name": "Alice", "age": 30}"#;
    /// let value = JsonUtil::parse(json_str);
    /// match value {
    ///     Ok(v) => log::info!("Parsed JSON Value: {}", v),
    ///     Err(e) => log::info!("Error parsing JSON: {}", e),
    /// }
    /// ```
    pub fn parse(json_str: &str) -> Result<Value, io::Error> {
        serde_json::from_str(json_str)
            .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Parse error: {}", e)))
    }

    /// 格式化 JSON 字符串
    ///
    /// # 参数
    /// * `json_str` - 要格式化的 JSON 字符串
    ///
    /// # 返回值
    /// 返回包含格式化后的 JSON 字符串的 `Result<String, io::Error>`
    ///
    /// # 示例
    /// ```
    /// let json_str = r#"{"name":"Alice","age":30,"is_student":true,"created_at":"2024-07-03 12:00:00"}"#;
    /// let formatted_json = JsonUtil::format(json_str);
    /// match formatted_json {
    ///     Ok(json) => log::info!("Formatted JSON: {}", json),
    ///     Err(e) => log::info!("Error formatting JSON: {}", e),
    /// }
    /// ```
    pub fn format(json_str: &str) -> Result<String, io::Error> {
        let value: Value = JsonUtil::parse(json_str)?;
        serde_json::to_string_pretty(&value)
            .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Format error: {}", e)))
    }
}

fn main() {
    // 示例用法
    #[derive(Serialize, Deserialize, Debug)]
    struct Person {
        name: String,
        age: u8,
        is_student: bool,
        created_at: String,
    }

    // 创建一个示例 Person 对象
    let person = Person {
        name: "Alice".to_string(),
        age: 30,
        is_student: true,
        created_at: JsonUtil::current_timestamp(),
    };

    // 序列化到 JSON 文件
    let file_path = "person.json";
    match JsonUtil::serialize_to_file(&person, file_path) {
        Ok(_) => log::info!("Serialized to file: {}", file_path),
        Err(e) => log::info!("Serialization failed: {}", e),
    }

    // 从 JSON 文件反序列化
    match JsonUtil::deserialize_from_file::<Person>(file_path) {
        Ok(deserialized_person) => log::info!("Deserialized from file: {:?}", deserialized_person),
        Err(e) => log::info!("Deserialization failed: {}", e),
    }

    // 格式化 JSON 字符串
    let json_str = r#"{"name":"Alice","age":30,"is_student":true,"created_at":"2024-07-03 12:00:00"}"#;
    match JsonUtil::format(json_str) {
        Ok(formatted_json) => log::info!("Formatted JSON: {}", formatted_json),
        Err(e)=> log::info!("Format failed: {}", e),
    }
}